import { useRefValue, useThrottle } from '@gnlab/utils/env-react'
import { Input } from 'antd'
import { Loading } from '@/desktop/components'
import type { TextRecord } from '@/services/contact-chat'
import { type Focusing, useSearch } from './logics'
import { Match } from './match'
import './search.module.less'

export function Search(props: {
  initialKeyword: string
  focusing: Focusing | null
  focus: (focusing: Focusing | null) => void
  goContact: (id: string) => void
}) {
  const { initialKeyword, focusing, focus, goContact } = props

  const { keyword, setKeyword, loading, full, nextPage, matches } = useSearch(initialKeyword)

  if (!matches.length && focusing) focus(null) // 每当 matches 被清空时，重置 focusing

  const loadingInfoRef = useRefValue({ loading, full })
  const matchesElementRef = useRef<HTMLDivElement>(null)
  const handleScroll = useCallback(() => {
    const { loading, full } = loadingInfoRef.current
    if (loading || full || !matchesElementRef.current) return
    const { offsetHeight, scrollHeight, scrollTop } = matchesElementRef.current
    if (scrollHeight - (scrollTop + offsetHeight) < offsetHeight) void nextPage() // 只要待展示的区域小于一屏了，就触发加载
  }, [nextPage])

  const throttledHandleScroll = useThrottle(handleScroll, 500)

  // 应对内容长度变化而需要加载后续内容的情况，每秒钟固定检查一次
  useEffect(() => {
    const intervalId = setInterval(handleScroll, 1000)
    return () => clearInterval(intervalId)
  }, [handleScroll])

  // ========================================

  return <div styleName="search-column">
    <header>
      <Input
        defaultValue={initialKeyword}
        onChange={e => void setKeyword(e.target.value)}
        placeholder="输入搜索关键词"
      />
    </header>

    <div styleName="matches" onScroll={throttledHandleScroll} ref={matchesElementRef}>
      {matches.map((match, index) => <Match
        key={`${match.conversationId}-${index}`}
        match={match}
        keyword={keyword}
        focusingRecord={focusing?.match === match ? focusing.record : null}
        focusRecord={(record: TextRecord) => focus({ match, record })}
        goContact={goContact}
      />)}

      {loading ? <Loading /> : null}

      {!keyword ? <div styleName="tips">请输入搜索关键词</div> : null}
      {keyword && !loading && !matches.length ? (
        <div styleName="tips">没有匹配的聊天记录</div>
      ) : null}
    </div>
  </div>
}
